<?php

namespace App\Http\Controllers\API\Admin;

use App\Http\Requests\API\CreateGoodsAPIRequest;
use App\Http\Requests\API\UpdateGoodsAPIRequest;
use App\Models\Cart;
use App\Models\Category;
use App\Models\Goods;
use App\Models\GoodsAttribute;
use App\Models\GoodsAttributeType;
use App\Models\GoodsContent;
use App\Models\GoodsNumberLog;
use App\Models\GoodsSlideshow;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Repositories\GoodsRepository;
use App\ZL\Controllers\ApiBaseController;
use EasyWeChat\Support\Attribute;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use Illuminate\Support\Facades\Auth;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class GoodsController
 * @package App\Http\Controllers\API
 */

class GoodsAPIAdminController extends ApiBaseController
{
    /** @var  GoodsRepository */
    private $goodsRepository;
    protected $model_name = 'App\Models\Goods';
    protected $model_load_array = [
        'categories','attributes','contents','slideshow'
    ];

    protected $search_field_array = [
//        'name'
    ];

    public function __construct(GoodsRepository $goodsRepo)
    {
        $this->goodsRepository = $goodsRepo;
    }

    public function authLimit(&$model)
    {
        $type = \request('type');
        $cat_id = \request('cat_id',false);
        $shop = Auth::guard('admin')->user()->shop;
        $res = [['status',1]];
        $res[] =  ['shop_id', $shop->id];
        if($type){
            if($type=='bargain_price'){
                $res[] =  ['sale_price', '>', 0];
            }
        }
        if($cat_id){
            $goods_ids = Category::find($cat_id)->goods()->pluck('goods_id')->toArray();
            $model = $model->whereIn('id',$goods_ids);
        }
        return $res;
    }

    public function index(Request $request)
    {
        $category_id = \request('category_id');
        $is_all = \request('is_all', null);
        $name = \request('name', null);
        $model = $this->modelPipeline([
            'modelGetAuthLimit',
            'modelGetSearch',
            'modelGetSort',
        ]);
//        if($name){
//            if(strstr($name,'[')!==false || strstr($name,'{')!==false){
//                $name = json_decode($name,true);
//                $name = $name[1];
//                $name = str_replace('%','',$name);
//            }
//            $name_array = zhong_wen_math($name);
//            $model = $model->where(function ($query)use($name_array){
//                foreach ($name_array as $item=>$_array) {
//                    if($item==0){
//                        $query->where('name', 'like', "%$_array%");
//                    }else{
//                        $query->orWhere('name', 'like', "%$_array%");
//                    }
//                }
//            });
//        }
        if($category_id){
            $cate_ids = [];
            $cate = Category::find($category_id);
            foreach ($cate->goods as $goods) {
                $cate_ids[] = $goods->id;
            }
            $model = $model->whereIn('id',$cate_ids);
        }
//        if(!$is_all){
//            $model = $model->where('is_on_sale', 1);
//            $model = $model->where('sale_start_date', '<=', date('Y-m-d H:i:s'));
//            $model = $model->where('sale_end_date', '>=', date('Y-m-d H:i:s'));
//        }
        $model_data = clone $model;
        $count = $model->count();
        $pageSize = request('pageSize',99999999999);
        $pagination = request('pagination',1);
        $pagination = $pagination>0?$pagination:1;
        //分页获取信息
        $model_data = $model_data->orderBy('number', 'desc')->skip($pageSize*($pagination-1))->take($pageSize)->get();

        $list = $this->modelPipeline([
            'collectionGetLoads',
            'modelByAfterGet',
        ],$model_data);

        return responseZK(1,$list,'',['count'=>$count]);
    }

    public function _after_get($data)
    {
        $data->load('categories');
        $data->load('attributes');
        $data->load('contents');
        $data->load('slideshow');

        return $data;
    }

    public function _after_find(&$data)
    {
        $data->categories;
        $data->attributes;
        $data->contents;
        $data->slideshow;
        $data = $data;
    }

    public function beforeStore($id, $request)
    {
        $shop = Auth::guard('admin')->user()->shop;
        $goods = Goods::find($id);
        if(isset($request['attributes'])){
            //属性
            $attributes = $request['attributes'];
            if(is_string($attributes))
                $attributes = json_decode($attributes,true);

            $attribute_types = [];
            if($attributes){
                foreach ($attributes as $attribute) {
                    $_key = $attribute['key'];
                    $attribute['key'] = json_encode($attribute['key'],256);
                    foreach ($_key as $_v) {
                        if(!isset($attribute_types[$_v[0]])){
                            $attribute_types[$_v[0]] = [];
                        }
                        $attribute_types[$_v[0]][] = $_v[1];
                        $attribute_types[$_v[0]] = array_unique($attribute_types[$_v[0]]);
                    }
                    $attribute['goods_id'] = $id;
                    if(!isset($attribute['id']) || !$attribute['id']){
                        GoodsAttribute::create($attribute);
                    }else{
                        GoodsAttribute::where('id',$attribute['id'])->update($attribute);
                    }
                }
            }
            //保存单个商品的属性类型
            if(count($attribute_types)>0){
                foreach ($attribute_types as $name=>$attribute_type) {
                    GoodsAttributeType::create([
                        'shop_id'=>$shop->id,
                        'goods_id'=>$id,
                        'name'=>$name,
                        'options'=>implode(',', $attribute_type),
                    ]);
                }
            }
        }

        $slideshows = $request['slideshows'];
        $content_images = $request['content_images'];
        //轮播图
        if(is_string($slideshows))
            $slideshows = explode(',',$slideshows);
        if($slideshows){
            foreach ($slideshows as $slideshow) {
                $_goodsSlideshow = new GoodsSlideshow([
                    'url'=>$slideshow
                ]);
                $goods->slideshow()->save($_goodsSlideshow);
            }
        }
        //详情图
        if(is_string($content_images))
            $content_images = explode(',',$content_images);
        if($content_images){
            foreach ($content_images as $content_image) {
                $_content = new GoodsContent([
                    'url'=>$content_image
                ]);
                $goods->contents()->save($_content);
            }
        }
        $cate_id = $request['cat_id'];
//        $cate_id = $cate?$cate:$request['cate_id'];
        if(is_string($cate_id))
            $cate_id = explode(',',$cate_id);
        $goods->categories()->sync($cate_id);
        $goods->shop_id = $shop->id;
        $goods->save();
        $this->goodsRepository->generateAttributeTypesByGoodsId($goods->id,$shop->id);
        return responseZK(1,$goods);
    }

    public function beforeUpdate($id, $request)
    {
        $shop = Auth::guard('admin')->user()->shop;
        $goods = Goods::find($id);
        $attributes = $request['attributes'];
        $slideshows = $request['slideshows'];
        $content_images = $request['content_images'];
        if(is_string($attributes)){
            $attributes = json_decode($attributes,true);

            $_attr_ids = [];

            $attribute_types = [];

            if($attributes){
                foreach ($attributes as $attribute) {
                    $_key = $attribute['key'];
                    $attribute['key'] = json_encode($attribute['key'],256);
                    if($_key){
                        foreach ($_key as $_v) {
                            if(!isset($attribute_types[$_v[0]])){
                                $attribute_types[$_v[0]] = [];
                            }
                            $attribute_types[$_v[0]][] = $_v[1];
                            $attribute_types[$_v[0]] = array_unique($attribute_types[$_v[0]]);
                        }
                        $attribute['goods_id'] = $id;
                        if(!isset($attribute['id']) || !$attribute['id']){
                            $_attr = GoodsAttribute::create($attribute);
                            $_attr_id = $_attr->id;
                        }else{
                            $_attr_id = $attribute['id'];
                            GoodsAttribute::where('id',$attribute['id'])->update($attribute);
                            if($attribute['number']>0){
                                Cart::where([
                                    ['number','>',$attribute['number']],
                                    ['goods_id','=',$id],
                                    ['attribute_id','=',$attribute['id']],
                                ])->update(['number'=>$attribute['number']]);
                            }
                        }
                        $_attr_ids[] = $_attr_id;
                    }
                }
            }
            //保存单个商品的属性类型
            GoodsAttributeType::where('goods_id',$id)->delete();
            if(count($attribute_types)>0){
                foreach ($attribute_types as $name=>$attribute_type) {
                    GoodsAttributeType::create([
                        'shop_id'=>$shop->id,
                        'goods_id'=>$id,
                        'name'=>$name,
                        'options'=>implode(',', $attribute_type),
                    ]);
                }
            }
            GoodsAttribute::whereNotIn('id', $_attr_ids)->delete();
        }
        //轮播图
        GoodsSlideshow::where('goods_id',$goods->id)->update(['goods_id'=>0]);
        if(is_string($slideshows))
            $slideshows = explode(',',$slideshows);
        if($slideshows){
            foreach ($slideshows as $slideshow) {
                $_goodsSlideshow = new GoodsSlideshow([
                    'url'=>$slideshow
                ]);
                $goods->slideshow()->save($_goodsSlideshow);
            }
        }
        GoodsContent::where('goods_id',$goods->id)->delete();
        //详情图
        if(is_string($content_images))
            $content_images = explode(',',$content_images);
        if($content_images){
            foreach ($content_images as $content_image) {
                $_content = new GoodsContent([
                    'url'=>$content_image
                ]);
                $goods->contents()->save($_content);
            }
        }
        $cate_id = $request['cat_id'];
//        $cate_id = $cate?$cate:$request['cate_id'];
        if(is_string($cate_id))
            $cate_id = explode(',',$cate_id);
        $goods->categories()->sync($cate_id);
        $goods->shop_id = $shop->id;
        $goods->save();
        $this->goodsRepository->generateAttributeTypesByGoodsId($goods->id,$shop->id);
        return responseZK(1,$goods);
    }
}
